{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-10-15T02:57:36.780347Z",
     "start_time": "2025-10-15T02:57:36.771324Z"
    }
   },
   "source": [
    "from sklearn.datasets import load_iris\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import accuracy_score\n",
    "import pandas as pd\n",
    "import numpy as np\n"
   ],
   "outputs": [],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-15T02:57:39.942723Z",
     "start_time": "2025-10-15T02:57:39.918132Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1. 加载鸢尾花数据集\n",
    "iris = load_iris()\n",
    "X = iris.data  # 特征矩阵\n",
    "y = iris.target  # 标签（0, 1, 2）\n",
    "# 2. 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.3, random_state=42, stratify=y  # 分层抽样，保持类别比例\n",
    ")\n",
    "# 3. 定义三种核函数的SVM模型，并分别训练和预测\n",
    "kernels = ['linear', 'poly', 'rbf']\n",
    "accuracies = {}\n",
    "for kernel in kernels:\n",
    "    # 创建SVM分类器\n",
    "    clf = SVC(kernel=kernel, random_state=42)\n",
    "    # 训练模型\n",
    "    clf.fit(X_train, y_train)\n",
    "    # 预测\n",
    "    y_pred = clf.predict(X_test)\n",
    "    # 计算准确率\n",
    "    acc = accuracy_score(y_test, y_pred)\n",
    "    accuracies[kernel] = acc\n",
    "    print(f\"{kernel} 核函数的准确率: {acc:.4f}\")"
   ],
   "id": "560ce9dd01cc7d53",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "linear 核函数的准确率: 1.0000\n",
      "poly 核函数的准确率: 0.9556\n",
      "rbf 核函数的准确率: 0.9556\n"
     ]
    }
   ],
   "execution_count": 6
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
